<?php

namespace app\index\controller;

use classes\RedisClass;
use classes\TokenBucket;
use service\LogService;
use think\Controller;
use think\Db;
use think\facade\Cache;
use think\Queue;
use think\facade\Env;
use service\WechatService;

class Lottery extends Controller
{


    public function __construct()
    {

        parent::__construct();

        if (!Env::get('app_debug') && !isMobile()) {
            tip_alert('请在微信手机端访问！');
        }

        if (Env::get('app_debug')) {
            session('wxd_openid', 'o6rBgxER1najTK-KGVmQSa9iPZig');
        }

    }

    function auth($url = '')
    {

        if (!empty($url)) {
            session('callback_url', $url);
        }
        if (isset($_GET['code']) && !empty($_GET['code'])) {
            $appid = sysconf('wechat_appid');
            $appsecret = sysconf('wechat_appsecret');
            $code = $_GET['code'];
            $weixinurl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid . "&secret=" . $appsecret . "&code=" . $code . "&grant_type=authorization_code ";
            //获取openid
            $res = curl($weixinurl);
            $token = json_decode($res, true);

            if (isset($token['openid'])) {
                $openid = $token['openid'];
                session("wxd_openid", $openid);
                $callback_url = session('callback_url');
                header("Location:$callback_url");
                exit(0);

            }
        } else {
            if (Env::get('app_debug')) {
                $this->redirect('http://sy.zoudingyong.com/codetoany/getcode.php?auk=demo1');
            } else {
                $this->redirect('http://sy.zoudingyong.com/codetoany/getcode.php?auk=xljvote');
            }

        }


    }

    /**
     * 抽奖展示页
     * @return mixed
     */
    public function lottery_show()
    {

        $wecha_id = session("wxd_openid");
        if (!$wecha_id) {
            $this->auth($this->request->url(true));
        }
        $config = RedisClass::get_vote_config_info();
        //开启流量限制
        if ($config['total_limit_status'] && !TokenBucket::get()) {
            $this->redirect($config['total_jump_url']);
        }
        $lottery = RedisClass::get_lottery_config_info();
        $banner = RedisClass::get_banner_info();
        $LotteryLeftCount = Cache::store('redis')->handler()->LLEN('lottery:wecha_id:' . $wecha_id);//抽奖剩余次数

        //分享朋友圈
        $current_url = $this->request->url(true);
        try {
            $wx_config = [
                'appid' => sysconf('wechat_appid'),
                'appsecret' => sysconf('wechat_appsecret'),
            ];
            $wechat = \WeChat\Script::instance($wx_config);
            $signPackage = $wechat->getJsSign($current_url);
        } catch (\Exception $e) {
            $signPackage = [
                'appId' => sysconf('wechat_appid'),
                'timestamp' => '',
                'nonceStr' => '',
                'signature' => '',
            ];
        };

        $prize_list = [
            ['text' => '谢谢参与'],
            ['text' => '一等奖'],
            ['text' => '二等奖'],
            ['text' => '三等奖'],
        ];

        return $this->fetch('lottery', [
            'config' => $config,
            'lottery' => $lottery,
            'banner' => $banner,
            'prize_list' => json_encode($prize_list),
            'LotteryLeftCount' => $LotteryLeftCount,
            'current_url' => $current_url,
            'signPackage' => $signPackage,
        ]);
    }

    /**
     *抽奖逻辑
     */
    public function lottery()
    {

        header("Access-Control-Allow-Origin: *");
        $wecha_id = session("wxd_openid");
        if (!$wecha_id) {
            $this->auth($this->request->url(true));
        }

        $config = RedisClass::get_vote_config_info();

        if ($config['switch']) {
            return json(['success' => 0, 'prizetype' => 12, 'text' => '网络异常,请稍后再试']);
        }
//        return json(['success' => 0, 'prizetype' => 4, 'text' => 13454544]);
//        return json(['success' => 0, 'prizetype' => 3, 'text' => '网络超时，请检查您的网络设置！']);

        if (!$wecha_id) {
            return json(['success' => 0, 'prizetype' => 7, 'text' => '网络超时，请检查您的网络设置！']);
        }

        return $data = $this->prizeHandle($wecha_id);
    }

    /**
     * 我的奖品
     * @return mixed
     */
    public function myprizes()
    {

        $wecha_id = session("wxd_openid");
        if (!$wecha_id) {
            $this->auth($this->request->url(true));
        }
        $config = RedisClass::get_vote_config_info();
        //开启流量限制
        if ($config['total_limit_status'] && !TokenBucket::get()) {
            $this->redirect($config['total_jump_url']);
        }
        $prizeItemss = Db::name('tp_lottery_record')
            ->where([
                'wecha_id' => $wecha_id,
                'islottery' => 1,
                'typeid' => 1,
            ])
//            ->cache('myprizes_' . $wecha_id . '_1', 3600 * 12)
            ->page(1, 10)
            ->order('id desc')
            ->select();
        $total_count = Db::name('tp_lottery_record')
            ->where([
                'wecha_id' => $wecha_id,
                'islottery' => 1,
            ])
//            ->cache('total_count_myprizes_' . $wecha_id, 3600 * 12)
            ->count();
        $banner = RedisClass::get_banner_info();

        //分享朋友圈
        $current_url = $this->request->url(true);
        try {
            $wx_config = [
                'appid' => sysconf('wechat_appid'),
                'appsecret' => sysconf('wechat_appsecret'),
            ];
            $wechat = \WeChat\Script::instance($wx_config);
            $signPackage = $wechat->getJsSign($current_url);
        } catch (\Exception $e) {
            $signPackage = [
                'appId' => sysconf('wechat_appid'),
                'timestamp' => '',
                'nonceStr' => '',
                'signature' => '',
            ];
        };

        return $this->fetch('myprizes', [
            'config' => $config,
            'banner' => $banner,
            'prizeItemss' => $prizeItemss,
            'total_count' => $total_count,
            'current_url' => $current_url,
            'signPackage' => $signPackage,
        ]);
    }

    /**
     * 我的报名奖品
     * @return mixed
     */
    public function my_reg_prizes()
    {

        $wecha_id = session("wxd_openid");
        if (!$wecha_id) {
            $this->auth($this->request->url(true));
        }
        $config = RedisClass::get_vote_config_info();

        $prizeItemss = Db::name('tp_lottery_record')
            ->where([
                'wecha_id' => $wecha_id,
                'typeid' => 2,
            ])
            ->cache('my_reg_prizes_' . $wecha_id, 3600)
            ->order('id desc')
            ->select();
        $banner = RedisClass::get_banner_info();

        //分享朋友圈
        $current_url = $this->request->url(true);
        try {
            $wx_config = [
                'appid' => sysconf('wechat_appid'),
                'appsecret' => sysconf('wechat_appsecret'),
            ];
            $wechat = \WeChat\Script::instance($wx_config);
            $signPackage = $wechat->getJsSign($current_url);
        } catch (\Exception $e) {
            $signPackage = [
                'appId' => sysconf('wechat_appid'),
                'timestamp' => '',
                'nonceStr' => '',
                'signature' => '',
            ];
        };
        return $this->fetch('my_reg_prizes', [
            'config' => $config,
            'banner' => $banner,
            'prizeItemss' => $prizeItemss,
            'current_url' => $current_url,
            'signPackage' => $signPackage,
        ]);
    }


    //异步加载
    public function get_list()
    {
        $wecha_id = session("wxd_openid");
        if (!$wecha_id) {
            $this->auth($this->request->url(true));
        }
        $page = input('page') ?: 1;//当前页数
        $limit = input('limit') ?: 10;//每页条数
        $db = Db::name('tp_lottery_record')
            ->field('id,sn,time,prize,sendstutas,sendtime,note');
        $db->where('wecha_id', $wecha_id);
        $db->where('islottery', 1);
        $db->where('typeid', 1);

        $db->order('id desc');
        $db->page($page, $limit);
        $db->cache('myprizes_' . $wecha_id . '_' . $page, 3600 * 12);
        $data = $db->select();

        foreach ($data as $key => $value) {
            $data[$key]['sendstutas'] = $value['sendstutas'] ? '已兑换' : '待兑换';
            $data[$key]['sendtime'] = $value['sendstutas'] ? date('m-d H:i:s', $value['sendtime']) : '';
        }

        if (!empty($data)) {
            return json(['code' => 1, 'msg' => 'ok', 'data' => $data]);
        } else {
            return json(['code' => 0, 'msg' => 'fail', 'data' => []]);
        }

    }

    /*
	 * 经典的概率算法，
	 * $proArr是一个预先设置的数组，
	 * 假设数组为：array(100,200,300，400)，
	 * 开始是从1,1000 这个概率范围内筛选第一个数是否在他的出现概率范围之内，
	 * 如果不在，则将概率空间，也就是k的值减去刚刚的那个数字的概率空间，
	 * 在本例当中就是减去100，也就是说第二个数是在1，900这个范围内筛选的。
	 * 这样 筛选到最终，总会有一个数满足要求。
	 * 就相当于去一个箱子里摸东西，
	 * 第一个不是，第二个不是，第三个还不是，那最后一个一定是。
	 * 这个算法简单，而且效率非常 高，
	 * 关键是这个算法已在我们以前的项目中有应用，尤其是大数据量的项目中效率非常棒。
	 */
    protected function get_rand($proArr)
    {
        $result = '';
        //概率数组的总概率精度
        $proSum = array_sum($proArr);
        //概率数组循环
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset ($proArr);
        return $result;
    }

    protected function prizeHandle($wecha_id)
    {
        $today = date("Y-m-d");
        $tomorrow = strtotime(date("Y-m-d", strtotime("+1 day")));
        $now = time();
        $start = mktime(0, 0, 0, date("m", $now), date("d", $now), date("Y", $now));
        $end = mktime(23, 59, 59, date("m", $now), date("d", $now), date("Y", $now));

        $config = RedisClass::get_vote_config_info();
        $lottery = RedisClass::get_lottery_config_info();

        if (!$lottery['status']) {
            return json(['success' => 0, 'prizetype' => 11, 'text' => '活动未开启']);
        }

        /*if ($config['statdate'] > time()) {
            return json(['success' => 0, 'prizetype' => 9, 'text' => '活动未开始']);

        } elseif ($config['enddate'] < time()) {
            return json(['success' => 0, 'prizetype' => 10, 'text' => '活动已结束']);
        }*/

        if ($config['enddate'] < time()) {
            return json(['success' => 0, 'prizetype' => 10, 'text' => '活动已结束']);
        }

        if (!Cache::store('redis')->handler()->LPOP('lottery:wecha_id:' . $wecha_id)) {
            return json(['success' => 0, 'prizetype' => 6, 'text' => '抽奖次数已经用完']);
        }
        //删除一条抽奖机会
        Db::name('tp_lottery_num')->where('wecha_id', $wecha_id)->limit(1)->delete();

        //cheat
        if (Cache::store('redis')->handler()->LPOP('cheat:prize:1:' . $wecha_id)) {
            $sncode = $this->cheat_prize($lottery, $wecha_id, 1);
            return json(['success' => 0, 'prizetype' => $sncode > 1 ? 1 : 0, 'text' => $sncode]);
        }
//        if (Cache::store('redis')->handler()->LPOP('cheat:prize:2:' . $wecha_id)) {
//            $this->cheat_prize($lottery, $wecha_id, 2);
//        }
        //cheat


        $prizeType = intval($this->get_prize($lottery));
//        $day_count = Cache::store('redis')->handler()->zCount('lottery:day:prize:' . $prizeType, $start, $end);
        $day_count = Cache::store('redis')->handler()->LLEN('lottery:day:prize:' . $prizeType . ':time:' . $today);

        $sncode = '';
        if ($prizeType == 1) {
            //*******************************1等奖********************************************//

            if ($lottery['firstdaynums'] > $day_count && Cache::store('redis')->handler()->LPOP('lottery:prize:1')) {

                $sncode = mt_rand(100000000, 999999999);  //兑奖码
                Db::name('tp_lottery_record')->insert(array('typeid' => 1, 'wecha_id' => $wecha_id, 'islottery' => 1, 'sn' => $sncode, 'note' => $lottery['first'], 'time' => $now, 'prize' => intval($prizeType)));

                //日中奖数量限制
                Cache::store('redis')->handler()->LPUSH('lottery:day:prize:' . $prizeType . ':time:' . $today, 1); //队列
                Cache::store('redis')->handler()->expireat('lottery:day:prize:' . $prizeType . ':time:' . $today, $tomorrow);//设置过期时间

                return json(['success' => 0, 'prizetype' => $prizeType, 'text' => $sncode]);

            } else {
                Db::name('tp_lottery_record')->insert(array('typeid' => 1, 'wecha_id' => $wecha_id, 'islottery' => 0, 'sn' => '', 'note' => '', 'time' => $now, 'prize' => 0));
                return json(['success' => 0, 'prizetype' => 0, 'text' => $sncode]);
            }

            //******************************************************************************************//

        } elseif ($prizeType == 2) {

            //*******************************2等奖********************************************//

            if ($lottery['seconddaynums'] > $day_count && Cache::store('redis')->handler()->LPOP('lottery:prize:2')) {

                $sncode = mt_rand(100000000, 999999999);  //兑奖码
                Db::name('tp_lottery_record')->insert(array('typeid' => 1, 'wecha_id' => $wecha_id, 'islottery' => 1, 'sn' => $sncode, 'note' => $lottery['second'], 'time' => $now, 'prize' => intval($prizeType)));

                //日中奖数量限制
                Cache::store('redis')->handler()->LPUSH('lottery:day:prize:' . $prizeType . ':time:' . $today, 1); //队列
                Cache::store('redis')->handler()->expireat('lottery:day:prize:' . $prizeType . ':time:' . $today, $tomorrow);//设置过期时间

                return json(['success' => 0, 'prizetype' => $prizeType, 'text' => $sncode]);


            } else {
                Db::name('tp_lottery_record')->insert(array('typeid' => 1, 'wecha_id' => $wecha_id, 'islottery' => 0, 'sn' => '', 'note' => '', 'time' => $now, 'prize' => 0));
                return json(['success' => 0, 'prizetype' => 0, 'text' => $sncode]);
            }

            //***********************************************************************************************//

        } elseif ($prizeType == 3) {

            //*******************************3等奖********************************************//
            if ($lottery['thirddaynums'] > $day_count && Cache::store('redis')->handler()->LPOP('lottery:prize:3')) {

                $sncode = '';  //兑奖码

                $redpacketId = Cache::store('redis')->handler()->RPOP('redpacket:left');
                if ($redpacketId) {
                    $redinfo = $this->getRedPaceketInfo($redpacketId, 1);
                    $wx_momey = $redinfo['money'] * 100;
                    $money = $redinfo['money'];
                    //企业付款逻辑
                    $trade_no = build_order_no(9);
                    $payresult = $this->pay($wecha_id, $wx_momey, $trade_no);

                    if ($payresult) {

                        //日中奖数量限制
                        Cache::store('redis')->handler()->LPUSH('lottery:day:prize:' . $prizeType . ':time:' . $today, 1); //队列
                        Cache::store('redis')->handler()->expireat('lottery:day:prize:' . $prizeType . ':time:' . $today, $tomorrow);//设置过期时间

                        Db::name('tp_lottery_record')->insert(array('typeid' => 1, 'wecha_id' => $wecha_id, 'islottery' => 1, 'sn' => $sncode, 'remark' => $money, 'note' => $lottery['third'], 'time' => $now, 'sendtime' => $now, 'sendstutas' => 1, 'prize' => intval($prizeType)));

                        return json(['success' => 0, 'prizetype' => $prizeType, 'text' => $money]);
                    } else {
                        //还原红包
                        $this->getRedPaceketInfo($redpacketId, 0);
                        Cache::store('redis')->handler()->LPUSH('redpacket:left', $redpacketId);
                        Db::name('tp_lottery_record')->insert(array('typeid' => 1, 'wecha_id' => $wecha_id, 'islottery' => 0, 'sn' => '', 'note' => '', 'time' => $now, 'prize' => 0));
                        return json(['success' => 0, 'prizetype' => 0, 'text' => $sncode]);
                    }
                } else {
                    Db::name('tp_lottery_record')->insert(array('typeid' => 1, 'wecha_id' => $wecha_id, 'islottery' => 0, 'sn' => '', 'note' => '', 'time' => $now, 'prize' => 0));
                    return json(['success' => 0, 'prizetype' => 0, 'text' => $sncode]);
                }

            } else {
                Db::name('tp_lottery_record')->insert(array('typeid' => 1, 'wecha_id' => $wecha_id, 'islottery' => 0, 'sn' => '', 'note' => '', 'time' => $now, 'prize' => 0));
                return json(['success' => 0, 'prizetype' => 0, 'text' => $sncode]);
            }

            //***********************************************************************************************//

        } elseif ($prizeType == 4) {

            //*******************************4等奖********************************************//

            return $this->lotteryFour($lottery, $wecha_id, $day_count, $prizeType);

            //***********************************************************************************************//

        } else {
            Db::name('tp_lottery_record')->insert(array('typeid' => 1, 'wecha_id' => $wecha_id, 'islottery' => 0, 'sn' => '', 'note' => '', 'time' => $now, 'prize' => 0));
            return json(['success' => 0, 'prizetype' => 0, 'text' => $sncode]);


        }

    }

    /**
     * 抽中4等奖(方式1)
     * @param $lottery
     * @param $wecha_id
     * @param $day_count
     * @param $prizeType
     * @return mixed
     */
    protected function lotteryFour($lottery, $wecha_id, $day_count, $prizeType)
    {
        $today = date("Y-m-d");
        $tomorrow = strtotime(date("Y-m-d", strtotime("+1 day")));
        $sncode = '';  //兑奖码
        if ($lottery['fourdaynums'] > $day_count) {
            Db::name('tp_lottery_record')->insert(array('typeid' => 1, 'wecha_id' => $wecha_id, 'islottery' => 1, 'sn' => $sncode, 'note' => $lottery['four'], 'time' => time(), 'prize' => intval($prizeType)));

            //日中奖数量限制
            Cache::store('redis')->handler()->LPUSH('lottery:day:prize:' . $prizeType . ':time:' . $today, 1); //队列
            Cache::store('redis')->handler()->expireat('lottery:day:prize:' . $prizeType . ':time:' . $today, $tomorrow);//设置过期时间

            return json(['success' => 0, 'prizetype' => $prizeType, 'text' => $sncode]);

        } else {
            Db::name('tp_lottery_record')->insert(array('typeid' => 1, 'wecha_id' => $wecha_id, 'islottery' => 0, 'sn' => '', 'note' => '', 'time' => time(), 'prize' => 0));
            return json(['success' => 0, 'prizetype' => 0, 'text' => $sncode]);
        }


    }

    /**
     * 抽中4等奖(方式, 发送券码，提前批量生成券码，发一个减一个）
     * @param $lottery
     * @param $wecha_id
     * @param $day_count
     * @param $prizeType
     * @return mixed
     */
    protected function lotteryFour2($lottery, $wecha_id, $day_count, $prizeType)
    {

        $today = date("Y-m-d");
        $tomorrow = strtotime(date("Y-m-d", strtotime("+1 day")));
        $sncode = '';  //兑奖码
        if ($lottery['fourdaynums'] > $day_count) {

            $couponId = Cache::store('redis')->handler()->LPOP('jj_coupon:left');
            if ($couponId) {

                //日中奖限制
                Cache::store('redis')->handler()->LPUSH('lottery:day:prize:' . $prizeType . ':time:' . $today, 1); //队列
                Cache::store('redis')->handler()->expireat('lottery:day:prize:' . $prizeType . ':time:' . $today, $tomorrow);//设置过期时间

                $sncode = $couponId;
                Db::name('tp_lottery_record')->insert(array('typeid' => 1, 'wecha_id' => $wecha_id, 'islottery' => 1, 'sn' => $sncode, 'note' => $lottery['four'], 'time' => time(), 'sendtime' => time(), 'sendstutas' => 1, 'prize' => intval($prizeType)));
                $this->updateCouponInfo($couponId, 1);
                return json(['success' => 0, 'prizetype' => $prizeType, 'text' => $sncode]);
            } else {
                Db::name('tp_lottery_record')->insert(array('typeid' => 1, 'wecha_id' => $wecha_id, 'islottery' => 0, 'sn' => '', 'note' => '', 'time' => time(), 'prize' => 0));
                return json(['success' => 0, 'prizetype' => 0, 'text' => $sncode]);
            }

        } else {
            Db::name('tp_lottery_record')->insert(array('typeid' => 1, 'wecha_id' => $wecha_id, 'islottery' => 0, 'sn' => '', 'note' => '', 'time' => time(), 'prize' => 0));
            return json(['success' => 0, 'prizetype' => 0, 'text' => $sncode]);
        }
    }

    protected function get_prize($lottery)
    {

        //奖品共 一等奖 3个，二等奖5个，三等奖10个
        //第一阶段: 一等奖2个，二等奖3个，三等奖7个
        //第一阶段: 一等奖1个，二等奖2个，三等奖3个
        $prize_arr = array(
            '0' => array('id' => 0, 'prize' => '未中奖', 'v' => $lottery['norate']),
            '1' => array('id' => 1, 'prize' => $lottery['first'], 'v' => $lottery['firstrate']),   //一等奖：5名  奖品：520元现金+520ML小郎酒 礼盒1提
            '2' => array('id' => 2, 'prize' => $lottery['second'], 'v' => $lottery['secondrate']),   //二等奖：30名  奖品：小郎酒520养生大礼包
            '3' => array('id' => 3, 'prize' => $lottery['third'], 'v' => $lottery['thirdrate']),   //三等奖：1000名  奖品：随机现金红包（1000元）
            '4' => array('id' => 4, 'prize' => $lottery['four'], 'v' => $lottery['fourrate']),   //幸运奖：不限  奖品：小郎酒商城优惠券（需链接到小郎酒商城）
        );
        $arr = [];
        foreach ($prize_arr as $key => $val) {
            $arr[$val['id']] = $val['v'];
        }
        $rid = $this->get_rand($arr); //根据概率获取奖项id

        $prizetype = $prize_arr[$rid]['id']; //中奖项

        return $prizetype;
    }

    protected function cheat_prize($lottery, $wecha_id, $prizetype)
    {

        if (Cache::store('redis')->handler()->LPOP('lottery:prize:' . $prizetype)) {
            if ($prizetype == 1) {
                $note = $lottery['first'];
            } elseif ($prizetype == 2) {
                $note = $lottery['second'];
            } else {
                $note = $lottery['third'];
            }

            $sncode = mt_rand(100000000, 999999999);  //兑奖码
            Db::name('tp_lottery_record')->insert(array('typeid' => 1, 'wecha_id' => $wecha_id, 'islottery' => 1, 'sn' => $sncode, 'note' => $note, 'time' => time(), 'prize' => $prizetype));
            Db::name('tp_lottery_cheat')->where([
                'wecha_id' => $wecha_id,
                'prizetype' => $prizetype
            ])->setField('status', 1);

            //清除缓存
            RedisClass::clear_prizes_cache($wecha_id);
            return $sncode;

        } else {
            Db::name('tp_lottery_record')->insert(array('typeid' => 1, 'wecha_id' => $wecha_id, 'islottery' => 0, 'sn' => '', 'note' => '', 'time' => time(), 'prize' => 0));
            return 0;
        }

    }


    /**
     * 提交收货地址
     * @return mixed
     */
    public function delivery()
    {

        $wecha_id = session("wxd_openid");
        if (!$wecha_id) {
            $this->auth($this->request->url(true));
        }

        if (request()->isPost()) {
            $config = RedisClass::get_vote_config_info();
            $id = input('prize_id');
//            if ($config['statdate'] > time()) {
//                return json(['code' => 1, 'message' => '活动未开始']);
//
//            } elseif ($config['enddate'] < time()) {
//                return json(['code' => 1, 'message' => '活动已结束']);
//            }

            $record = Db::name('tp_lottery_record')->where('id', $id)->find();
            if ($record['wecha_id'] != $wecha_id) {
                return json(['code' => 1, 'message' => '非法操作!']);
            }

            if ($record['submit_time'] > 0) {
                return json(['code' => 1, 'message' => '请勿重复提交!']);
            }
            $data['name'] = input('name');
            $data['phone'] = input('mobile');
            $data['address'] = input('address');
            $data['submit_time'] = time();

            if ($result = Db::name('tp_lottery_record')->where('id', $id)->update($data)) {
                return json(['code' => 0, 'message' => '提交成功，将尽快安排发货！']);
            } else {
                return json(['code' => 1, 'message' => '提交失败,请稍后重新提交!']);
            }

        } else {
            return json(['code' => 1, 'message' => '提交失败!']);
        }

    }

    public function test()
    {

        $openid = 'o6rBgxER1najTK-KGVmQSa9iPZig';
        $money = input('money') ?: 1;
        print_dump($this->pay($openid, $money * 100, time()));
    }

    /**
     * 企业付款
     * @param $openid
     * @param $money
     * @param $trade_no
     * @return bool
     */
    protected function pay($openid, $money, $trade_no)
    {

        $config = [
            'appid' => sysconf('wechat_appid'),
            'appsecret' => sysconf('wechat_appsecret'),
            'mch_id' => config('wechat.mch_id'),
            'mch_key' => config('wechat.mch_key'),
            'ssl_cer' => config('wechat.ssl_cer'),
            'ssl_key' => config('wechat.ssl_key'),

        ];

        try {
            $wechat = \WeChat\Pay::instance($config);

            // 4. 组装参数，可以参考官方商户文档
            $options = [
                'partner_trade_no' => $trade_no,
                'openid' => $openid,
                'check_name' => 'NO_CHECK',
                'amount' => $money,
                'desc' => '测试',
                'spbill_create_ip' => $this->request->ip(0, true),
            ];
            $result = $wechat->createTransfers($options);
            if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
                return true;
            }
            $this->errorLog($result, $openid);
            return false;
//            $result = $wechat->queryTransfers($options['partner_trade_no']);
//            var_export($result);

        } catch (\Exception $e) {
            LogService::write('企业付款', "错误信息:{$e->getMessage()}");
            return false;
            // 出错啦，处理下吧
//            echo $e->getMessage() . PHP_EOL;

        }

    }

    /**
     * 日志记录
     */
    private function errorLog($result, $openid)
    {

        LogService::write('现金红包', "错误代码:{$result['err_code']},错误描述:{$result['err_code_des']},openID:{$openid}");

    }

    /**
     * 查询红包
     */
    public function chaxunRedPack($trade_no)
    {

        $config = [
            'appid' => sysconf('wechat_appid'),
            'appsecret' => sysconf('wechat_appsecret'),
            'mch_id' => config('wechat.mch_id'),
            'mch_key' => config('wechat.mch_key'),
            'ssl_cer' => config('wechat.ssl_cer'),
            'ssl_key' => config('wechat.ssl_key'),

        ];

        try {
            $wechat = \WePay\Redpack::instance($config);

            // 发送红包记录
            $result = $wechat->query($trade_no);
            print_dump($result);
            if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
                return true;
            }
            return false;
        } catch (\Exception $e) {
            print_dump($e->getMessage());
            return false;
            // 出错啦，处理下吧
//            echo $e->getMessage() . PHP_EOL;

        }

    }

    /**
     * 获取红包金额
     * @param $redpacketId
     * @param $status
     * @return array|null|\PDOStatement|string|\think\Model
     */
    private function getRedPaceketInfo($redpacketId, $status)
    {

        $redpacket = Db::name('tp_redpacket')->find($redpacketId);
        Db::name('tp_redpacket')->where('id', $redpacketId)->setField('status', $status);
        return $redpacket;
    }

    /**
     * 更新小郎酒优惠券
     * @param $couponId
     * @param $status
     * @return int
     */
    private function updateCouponInfo($couponId, $status)
    {

        $result = Db::name('tp_coupon')->where('code', $couponId)->setField('status', $status);
        return $result;
    }


    private function make_password($length = 8)
    {
        // 密码字符集，可任意添加你需要的字符
        $chars = array(
            'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
            'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
            't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',

        );

        // 在 $chars 中随机取 $length 个数组元素键名
        $keys = array_rand($chars, $length);
        $password = '';
        for ($i = 0; $i < $length; $i++) {
            // 将 $length 个数组元素连接成字符串
            $password .= $chars[$keys[$i]];
        }
        return $password;

    }


    private function make_code()
    {
        print_dump('ok2');
        $get = $this->request->get();
        $code = isset($get['t']) ? $get['t'] : '';
//        print_dump($code);

        for ($x = 1; $x <= 5; $x++) {
            Db::name('tp_card')->insert([
                'code' => md5($this->make_password(20) . 'xlj@2021'),
                'money' => '9.9',
            ]);
        }
        print_dump('ok');
    }

    public function update_code()
    {
        print_dump('ok2');
        $list = Db::name('tp_card')->select();

        foreach ($list as $one) {
            Db::name('tp_card')
                ->where('id', $one['id'])
                ->update([
                    'code' => md5($one['code'] . 'xlj@2021'),
                ]);
        }
        print_dump('ok');
    }
}
